package com.hs.user.exception;

import com.hs.common.api.dto.ResultCode;
import com.hs.common.api.dto.ResultVo;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全局异常
 */
@RestControllerAdvice
public class GlobalException {

    /**
     * 处理参数校验失败异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo handlerArgumentsNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        // 获取校验失败的字段的集合
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        // 获取校验失败的字段的message
        Map<String, String> collectErrorMap = fieldErrors.stream().collect(Collectors.toMap(
                FieldError::getField, FieldError::getDefaultMessage
        ));
        return new ResultVo(ResultCode.PARAM_IS_BLANK,collectErrorMap);
    }

    /**
     * 处理其他所有异常
     */
    @ExceptionHandler(Exception.class)
    public ResultVo handlerException(Exception e) {
        e.printStackTrace();
        return new ResultVo(ResultCode.FAILED);
    }

}
